package com.wiscamp.ninechapters.common.exception;

import cube.ddd.exception.YamlConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * 异常处理帮助类
 *
 * @author yifeng
 */
public class ExceptionCodeHelper {

    public static final String GETBYID_EXCEPTION_CODE = "general-exception.getbyid";

    public static final String GETBYIDS_EXCEPTION_CODE = "general-exception.getbyids";

    private static ExceptionCodeHelper instance;

    private static Properties generalExceptions;

    private static Properties dataExceptions;

    private static Properties serviceExceptions;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 单例
     *
     * @return
     */
    public static ExceptionCodeHelper getInstance() {
        if (instance == null) {
            generalExceptions = YamlConfig.getGeneralExceptions();
            dataExceptions = YamlConfig.getGeneralExceptions();
            serviceExceptions = YamlConfig.getGeneralExceptions();
            instance = new ExceptionCodeHelper();
        }
        return instance;
    }

    /**
     * 通过异常代码获取普通异常消息
     *
     * @param code
     * @return
     */
    public String getGeneralExceptionMessage(String code) {
        String message = generalExceptions.getProperty(code.toLowerCase());
        if (message == null || "".equals(message)) {
            logger.debug("Cannot find the message of a general exception: {}", code);
        }
        return message;
    }

    /**
     * 通过异常代码获取数据访问异常消息
     *
     * @param code
     * @return
     */
    public String getDataExceptionMessage(String code) {
        String message = dataExceptions.getProperty(code.toLowerCase());
        if (message == null || "".equals(message)) {
            logger.debug("Cannot find the message of a data exception: {}", code);
        }
        return message;
    }

    /**
     * 通过异常代码获取服务异常消息
     *
     * @param code
     * @return
     */
    public String getServiceExceptionMessage(String code) {
        String message = serviceExceptions.getProperty(code.toLowerCase());
        if (message == null || "".equals(message)) {
            logger.debug("Cannot find the message of a service exception: {}", code);
        }
        return message;
    }

    public String getAppServiceExceptionMessage(String code) {
        String message = serviceExceptions.getProperty(code.toLowerCase());
        if (message == null || "".equals(message)) {
            logger.debug("Cannot find the message of a application service exception: {}", code);
        }
        return message;
    }
}
